package com.hange.ymcc.service;

import com.alibaba.fastjson.JSONObject;
import com.hange.ymcc.constant.Regexconstant;
import com.hange.ymcc.domain.MediaFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

@Slf4j
@Component
public class ConsumerService {

    @Autowired
    private IMediaFileService mediaFileService;

	// MessageExt：是一个消息接收通配符，不管发送的是String还是对象，都可接收，当然也可以像上面明确指定类型（我建议还是指定类型较方便）
    @Service
    @RocketMQMessageListener(topic = Regexconstant.ROCKETMQ_TOPIC_MEDIA,
            selectorExpression = Regexconstant.ROCKETMQ_TAG,
            consumerGroup = "service-media-consumer")
    public class Consumer implements RocketMQListener<MessageExt> {
        @Override
        public void onMessage(MessageExt messageExt) {
            // 1. 获取到消息  MediaFile
            try {
                String jsonStrMediaFile = new String(messageExt.getBody(), "UTF-8");
                MediaFile mediaFile = JSONObject.parseObject(jsonStrMediaFile, MediaFile.class);

                // 调用推流方法
                mediaFileService.handleFile2m3u8(mediaFile);

            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
